using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using webapi.Domain;
using webapi.Domain.Repository;
using webapi.Infrastructure.Db;

namespace webapi.Infrastructure.Repository
{
    public class EFRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly webapiDbContext _db;

        private readonly DbSet<T> _table;
        public IQueryable<T> Table
        {
            get
            {
                return _table.AsNoTracking();
                // return _table as IQueryable<T>;
            }
        }

        public EFRepository(webapiDbContext db)
        {
            _db = db;
            _table = _db.Set<T>();
        }


        public T Add(T entity)
        {
            entity.IsActived = true;
            entity.IsDeleted = false;
            entity.CreatedAt = DateTime.Now;
            entity.UpdatedAt = DateTime.Now;
            entity.DisplayOrder = 0;

            _table.Add(entity);
            _db.SaveChanges();

            return entity;
        }
        public T getById(Guid id)
        {
            // var entity = _table.Where(x => x.Id == id && x.IsDeleted == false).FirstOrDefault();
            var entity =
               _db
                   .Set<T>()
                   .AsQueryable()
                   .Where(x => x.Id == id)
                   .FirstOrDefault();
            return entity;
        }

        public void Update(T entity)
        {
            entity.UpdatedAt = DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }

        public void Delete(T entity)
        {
            _table.Update(entity);
            _db.SaveChanges();
        }
    }
}